<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/18
 * Time: 13:21
 */

namespace app\admin\model;
use think\Model;

class ApiList extends Model
{
    protected $table = 'snake_api_list';

    public $methodList = [
        1 => 'post',
        2 => 'get',
        3 => 'delete',
        4 => 'put',
        5 => 'patch',
    ];

    public $fieldType = [
        1 => 'str',
        2 => 'int',
        3 => 'float',
    ];

    public $statusList = [
        0 => '禁止',
        1 => '正常',
        2 => '测试',
    ];

    public $paramType = [
        0 => '普通参数',
        1 => '文件'
    ];

    public $encryptList = [
        'md5',
        'base64_encode',
        'urlencode'
    ];
    public $validatesign = [
       '0'=>'不需验证',
       '1'=> '需验证',
    ];
    /**
     * 查询接口列表
     * @param $where
     * @param $offset
     * @param $limit
     */
    public function getApiListByWhere($where, $offset, $limit){
        return self::where($where)->limit($offset, $limit)->order('id desc')->select();
    }

    /**
     * 根据搜索条件获取所有的接口总数
     * @param $where
     */
    public function getAllApiList($where){
        return self::where($where)->count();
    }

    /**
     * 插入
     *
     * @param $param
     * @return array
     * @throws \Exception
     */
    public function insertApi($param){
        self::startTrans();
        try{
            $filter = ['group_id','title', 'url', 'method', 'path'];
            foreach ($filter as $v) {
                if (!isset($param[$v]) || empty($param[$v])) {
                    throw new \Exception($v . ' 参数错误');
                }
            }
            /**
             * 是否存在
             */
            if ($this->where(['title' => $param['title']])->find()) {
                throw new \Exception('接口地址已经存在');
            }

            $param['sn'] = self::getSn();
            $param['create_time'] = time();
            if (!$id = $this->allowField(true)->insertGetId($param)) {
                throw new \Exception(' 添加失败');
            }

            $fields = [];
            if (isset($param['request']) && count($param['request']) > 0) {
                foreach ($param['request'] as $k => $v) {
                    if (empty($v['name']) || empty($v['title'])) {
                        continue;
                    }
                    $field_list = [];
                    $field_list['api_id'] = $id;
                    $field_list['name'] = $v['name'];
                    $field_list['title'] = $v['title'];
                    $field_list['length'] = $v['length'];
                    $field_list['type'] = $v['type'];
                    $field_list['filter'] = $v['filter'];
                    $field_list['is_file'] = $v['is_file'];
                    $field_list['request'] = 1;
                    $fields[] = $field_list;
                }
                unset($param['request']);
            }
            if (isset($param['response']) && count($param['response']) > 0) {
                foreach ($param['response'] as $k => $v) {
                    if (empty($v['name']) || empty($v['title'])) {
                        continue;
                    }
                    $field_list = [];
                    $field_list['api_id'] = $id;
                    $field_list['name'] = $v['name'];
                    $field_list['title'] = $v['title'];
                    $field_list['length'] = $v['length'];
                    $field_list['type'] = $v['type'];
                    $field_list['filter'] = $v['filter'];
                    $field_list['request'] = 2;
                    $fields[] = $field_list;
                }
                unset($param['response']);
            }
            if (count($fields) > 0) {
                if (!(new Field())->insertAll($fields)) {
                    throw new \Exception(' 参数写入失败');
                }
            }

        self::commit();
        }catch (\Exception $e){
            self::rollback();
            return msg(-2, '', $e->getMessage());
        }
        return msg(1, url('user/index'), '添加成功');
    }



    public static function getSn($length = 6)
    {
        $sn = substr(md5(microtime(true)), 0, $length);

        if (self::where(['sn' => $sn])->find()) {
            $sn = self::getSn();
        }

        return strtoupper($sn);
    }
    public function getMethodAttr($key)
    {
        return $this->methodList[$key];
    }
    public function getStatusAttr($key)
    {
        return $this->statusList[$key];
    }
    public function getValidateSignAttr($key)
    {
        return $this->validatesign[$key];
    }
    public function getValidateTimeAttr($key)
    {
        return $this->validatesign[$key];
    }

    public function getMethodList()
    {
        return $this->methodList;
    }
    public function getStatusList()
    {
        return $this->statusList;
    }
}